# -*- coding: utf-8 -*-
"""
@ Created on 2024-06-14 12:23
---------
@summary: 字典项API实现
---------
@author: Lsaiah
"""

from fastapi import APIRouter, Depends, Query
from typing import Optional
from core.auth import AuthHandler
from component.abstractCrud import AbstractCRUD
from core.response import ResponseModel, ListResponseModel
from ..models.form.dict_item_form import DictItemCreateRequest, DictItemUpdateRequest
from ..models.curd.dict_item_crud import DictItem, DictItemCRUD
from constant import *

dict_item_router = APIRouter(prefix="/system/dict/item", tags=["系统字典项管理"])
auth_handler = AuthHandler()


class DictItemCRUDAPI(AbstractCRUD[DictItem, DictItemCreateRequest, DictItemUpdateRequest]):
    """字典项CRUD API实现类"""
    
    def __init__(self):
        super().__init__(
            model=DictItem,
            crud_class=DictItemCRUD,
            create_schema=DictItemCreateRequest,
            update_schema=DictItemUpdateRequest
        )
    
    def get_router(self):
        """获取路由"""
        return dict_item_router


# 创建实例
dict_item_crud_api = DictItemCRUDAPI()


@dict_item_router.get("/list", response_model=ResponseModel)
async def get_dict_items_list(
    current_user = Depends(auth_handler.get_current_active_user())
):
    """获取字典项列表"""
    try:
        items = await DictItemCRUD.get_list_all()
        item_list = []
        for item in items:
            item_data = {
                "id": item.id,
                "dict_type_id": item.dict_type.id if item.dict_type else None,
                "label": item.label,
                "value": item.value,
                "description": item.description,
                "is_active": item.is_active,
                "sort_order": item.sort_order,
                "created_at": item.created_at.isoformat(),
                "updated_at": item.updated_at.isoformat()
            }
            item_list.append(item_data)
        
        return ResponseModel.success(data=item_list)
        
    except Exception as e:
        return ResponseModel.error(
            message="获取字典项列表失败",
            code=CODE_ERROR
        )

# 注册路由
@dict_item_router.get("/page", response_model=ListResponseModel)
async def get_dict_items(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    is_active: Optional[bool] = Query(None, description="是否激活"),
    dict_type_id: Optional[int] = Query(None, description="字典类型ID"),
    current_user = Depends(auth_handler.get_current_active_user())
):
    """获取字典项列表"""
    filters = {}
    if dict_type_id is not None:
        filters["dict_type_id"] = dict_type_id
    
    return await dict_item_crud_api.page(page=page, size=size, search=search, is_active=is_active, **filters)


@dict_item_router.get("/get", response_model=ResponseModel)
async def get_dict_item(
    id: int = Query(..., description="字典项ID"),
    current_user = Depends(auth_handler.get_current_active_user())
):
    """获取字典项详情"""
    return await dict_item_crud_api.get(id=id)


@dict_item_router.post("/create", response_model=ResponseModel)
async def create_dict_item(
    dict_item_data: DictItemCreateRequest,
    current_user = Depends(auth_handler.get_current_active_user())
):
    """创建字典项"""
    return await dict_item_crud_api.create(data=dict_item_data)


@dict_item_router.put("/update", response_model=ResponseModel)
async def update_dict_item(
    dict_item_data: DictItemUpdateRequest,
    current_user = Depends(auth_handler.get_current_active_user())
):
    """更新字典项"""
    return await dict_item_crud_api.update(data=dict_item_data)


@dict_item_router.delete("/delete", response_model=ResponseModel)
async def delete_dict_item(
    id: int = Query(..., description="字典项ID"),
    current_user = Depends(auth_handler.get_current_active_user())
):
    """删除字典项"""
    return await dict_item_crud_api.delete(id=id)


@dict_item_router.get("/by-type", response_model=ResponseModel)
async def get_dict_items_by_type(
    dict_type_id: int = Query(..., description="字典类型ID"),
    current_user = Depends(auth_handler.get_current_active_user())
):
    """根据字典类型ID获取字典项列表"""
    try:
        items = await DictItemCRUD.get_by_dict_type_id(dict_type_id)
        item_list = []
        for item in items:
            item_data = {
                "id": item.id,
                "label": item.label,
                "value": item.value,
                "description": item.description,
                "is_active": item.is_active,
                "sort_order": item.sort_order,
                "created_at": item.created_at.isoformat(),
                "updated_at": item.updated_at.isoformat()
            }
            item_list.append(item_data)
        
        return ResponseModel.success(data=item_list)
        
    except Exception as e:
        return ResponseModel.error(
            message="获取字典项列表失败",
            code=CODE_ERROR
        )





